package com.example.demo01.Socket;

import com.example.demo01.VO.IPacketInstruction;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public   class CustomHeartbeatHandler extends SimpleChannelInboundHandler<IPacketInstruction> {

    private int heartbeatCount = 0;


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, IPacketInstruction packetInstruction) throws Exception {

        if (packetInstruction != null) {


            if(packetInstruction.getTelNo().equals("DX00")){

                heartbeatCount=0;
                log.info("HeartBeat DX00");
            }
            else{
                log.info("HeartBeat DX............");
                channelHandlerContext.fireChannelRead(packetInstruction);

            }

        }


    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception
    {
        IdleStateEvent event = (IdleStateEvent)evt;
        switch (event.state()){
            case READER_IDLE:
                heartbeatCount++;
                log.info("READER_IDLE "+ heartbeatCount);
                break;
        }
        if(heartbeatCount>3){
            log.info("server will disconnect client ...");
            ctx.channel().close();
        }
        else{
            super.userEventTriggered(ctx,evt);
        }
    }

}
